package cn.daniellee.regip.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

@RestController
@EnableAutoConfiguration
public class MainController {

	@Value("${location}")
	private String location;

	@ResponseBody
	@RequestMapping("/")
	String index(HttpServletRequest request) {
		String ipAddress;
		try {
			ipAddress = request.getHeader("x-forwarded-for");
			if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
				ipAddress = request.getHeader("Proxy-Client-IP");
			}
			if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
				ipAddress = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
				ipAddress = request.getRemoteAddr();
				if (ipAddress.equals("127.0.0.1")) {
					// 根据网卡取本机配置的IP
					InetAddress inet;
					try {
						inet = InetAddress.getLocalHost();
					} catch (UnknownHostException e) {
						e.printStackTrace();
						return "IP地址获取出错";
					}
					ipAddress = inet.getHostAddress();
				}
			}
			// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
			if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
				// = 15
				if (ipAddress.indexOf(",") > 0) {
					ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
				}
			}
		} catch (Exception e) {
			return "IP地址获取出错";
		}
		if (ipAddress != null) {
			File listFile = new File(location);
			if (!listFile.exists()) return "白名单读取失败";
			BufferedReader reader = null;
			BufferedWriter writer = null;
			try {
				List<String> ipList = new ArrayList<>();
				reader = new BufferedReader(new InputStreamReader(new FileInputStream(listFile), "UTF-8"));
				String temp;
				while ((temp = reader.readLine()) != null) {
					ipList.add(temp);
				}
				if (ipList.contains(ipAddress)) {
					return "IP地址已注册过";
				}
				writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(listFile, true), "UTF-8"));
				writer.write(ipAddress + "\n");
				writer.flush();
			} catch (Exception e) {
				e.printStackTrace();
				return "系统内部错误";
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException ignored) { }
				}
				if (writer != null) {
					try {
						writer.close();
					} catch (IOException ignored) { }
				}
			}
		}
		return "IP地址注册成功";
	}

}